﻿using System;
using K9Nano.Dependency;
using K9Nano.Domain;
using K9Nano.Share;

namespace K9Nano.Caching
{
    public class DefaultSharedUserCache : ISharedUserCache, IScopedDependency
    {
        protected readonly ITypedCache<SharedUserCacheItem> Cache;
        protected readonly IReadOnlyRepository ReadOnlyRepository;

        public DefaultSharedUserCache(IReadOnlyRepository readOnlyRepository, ITypedCache<SharedUserCacheItem> cache)
        {
            ReadOnlyRepository = readOnlyRepository;
            Cache = cache;
        }
        
        public SharedUserCacheItem Get(Guid id)
        {
            return Cache.GetOrAdd(id.ToString(), _ => GetUser(id), TimeSpan.FromDays(1));
        }

        protected virtual SharedUserCacheItem GetUser(Guid id)
        {
            var item = ReadOnlyRepository.QueryFirstOrDefault<SharedUserCacheItem>(
                $"select Id, UserName as Name, PhoneNumber as Phone, TenantId from {K9SharedConstants.SharedSchemePlaceholder}.asp_net_user where Id=@id",
                new { id = id.ToString() });
            if (item != null)
            {
                var name = ReadOnlyRepository.QueryFirstOrDefault<string>(
                    $"select ClaimValue from {K9SharedConstants.SharedSchemePlaceholder}asp_net_user_claim where UserId=@id and ClaimType='name'",
                    new { id = id.ToString() });
                if (!string.IsNullOrEmpty(name))
                {
                    item.Name = name;
                }
            }
            return item;
        }
    }
}